package com.frame.project.modules.test.sys.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.frame.project.core.aspect.webaspect.PageAnnotation;
import com.frame.project.core.exception.RestResultEntity;
import com.frame.project.core.exception.RestResult;
import com.frame.project.modules.test.sys.entity.SysUser;
import com.frame.project.modules.test.sys.service.SysUserService;
import com.github.pagehelper.PageInfo;


/**
 * 用户表
 * @author Administrator
 *
 */

@RequestMapping("api/sys/user")
@RestController 
public class SysUserController {

	private static final Logger logger = LogManager.getLogger(SysUserController.class); 

	@Autowired
	private SysUserService sysUserService;
	
	
	@RequestMapping("/save")
	public RestResultEntity<?>  save(@RequestBody @Validated  SysUser user, BindingResult result){
		return RestResult.genResult(user);
	}
	
	
	@PageAnnotation("controller")
	@RequestMapping({"list"})
	@RequiresAuthentication
	public RestResultEntity<PageInfo<SysUser>> list() {
		return RestResult.genResult(sysUserService.findList());
	}

	@RequestMapping({"count"})
	public int count() {
		return sysUserService.count();
	}
	

	@RequestMapping(value="/upload") 
	public String handleFileUpload(HttpServletRequest request) throws FileNotFoundException{ 
		List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		for (int i =0; i< files.size(); ++i) { 
			file = files.get(i); 
			if (!file.isEmpty()) { 
				try { 
					byte[] bytes = file.getBytes(); 
					
					stream = 	new BufferedOutputStream(new FileOutputStream(
									new File(file.getOriginalFilename()))); 
					stream.write(bytes); 
					stream.close(); 
				} catch (Exception e) { 
					stream =  null;
					return "You failed to upload " + i + " =>" + e.getMessage(); 
				} 
			} else { 
				return "You failed to upload " + i + " becausethe file was empty."; 
			} 
		} 
		return "upload successful"; 

	} 

}
